#!/bin/bash

#Created by Cheng 2015-1008
#Version 1.0

if [ $# -lt 1 ]; then
        echo `date +"%Y-%m-%d %H:%M:%S"`  "Usage: <DIRNUM> <ROOMNO>"
        exit 1
fi

SOURCEDATAPATH=/data02/data
TMPDATAPATH=/data02/streamsdata/tmpdata
BUFFDATAPATH=/data02/streamsdata/buff
WORKPATH=/data02/streamsdata/
DIRNUM=$1
ROOMNO=$2
FILESNAME=*${ROOMNO}*.gz

while true
do

DATE=`date +%Y%m%d`
LOGFILE=${WORKPATH}log/flume_idc_datamv_${ROOMNO}_${DATE}.log

        DATEDIR=`date +%Y%m%d`
#        FileNum=`ls ${SOURCEDATAPATH}/${DATEDIR}/*${ROOMNO}*.gz -lR|grep "^-"|wc -l`
        FileNum=`find ${SOURCEDATAPATH} -name "*.gz" |head -1000|wc -l`
#       FileNum=`ls ${SOURCEDATAPATH}/${DATEDIR}/*.gz -lR|grep "^-"|wc -l`
#        DirNum=`expr ${FileNum} / 2`
        echo 'FileNum is '${FileNum} | tee -a ${LOGFILE}
#        echo 'DirNum is '${DIRNUM} | tee -a ${LOGFILE}


     if (( $FileNum > 0 )); then

        echo 'move data from' ${SOURCEDATAPATH} 'to' ${TMPDATAPATH} | tee -a ${LOGFILE}
        mv `find ${SOURCEDATAPATH} -name "${FILESNAME}" | head -32` ${TMPDATAPATH}

        echo 'tar file.....' | tee -a ${LOGFILE}
        for tar in ${TMPDATAPATH}/*${ROOMNO}* ;do tar zxvf $tar -C ${BUFFDATAPATH}/ ;done | tee -a ${LOGFILE}

        echo 'remove tmpdata' | tee -a ${LOGFILE}
        rm -rf ${TMPDATAPATH}/*.gz

        COUNT=1
        while (( $COUNT<=$DIRNUM ))
        do
                DATAPATH=/data02/streamsdata/flumebuff${COUNT}
                if [ ! -d $DATAPATH ]; then
                        mkdir -p $DATAPATH | tee -a ${LOGFILE}
                fi;
    
                echo "move txt from ${BUFFDATAPATH} to flumebuff"$COUNT | tee -a ${LOGFILE}
                TargetFileNum=`ls ${DATAPATH}/*.txt -lR|grep "^-"|wc -l`
                if (( $TargetFileNum < 3 ));
                then
                        REMAINNUM=$[ 3 - $TargetFileNum ]
                        echo "remain num is ${REMAINNUM}" | tee -a ${LOGFILE}
                        if (( $REMAINNUM > 0 ));
                        then 
                                mv `find ${BUFFDATAPATH} -name "*${ROOMNO}*.txt" |sort -u|head -1`  ${DATAPATH}
                                echo `date +"%Y-%m-%d %H:%M:%S"`  "mv file success ${DATAPATH}"   | tee -a ${LOGFILE}
                        fi;
                fi;
                COUNT=$[COUNT+1]

        done
      fi;
        #       echo 'sleep.....start'
                sleep 3
        #       echo 'sleep....end'
done
